# -*- coding:utf8 -*-
from blog.controller.apis import get_categories

__author__ = 'cosven'

from bson.objectid import ObjectId
from flask import request, render_template, redirect

from blog import mongo
from blog.controller import apis
from flask.ext.login import login_required, current_user


@login_required
def admin_new():
    """
    暂时只处理: 新建一篇博客的情况
    """
    categories = apis.get_categories()
    drafts = mongo.db.draft.find({})
    drafts_list = []    # 不可以直接使用drafts，因为drafts会变化
    for draft in drafts:
        drafts_list.append(draft)
    draft_count = drafts.count()
    draft_id = mongo.db.draft.insert({})
    blog_id = ''
    return render_template('admin_new.html', **locals())

@login_required
def admin_edit(_id):
    """
    fix 15-2-25: 首先检测有没有相应的已经保存的草稿,如果有，则重定向

    修改一篇博客,处理编辑页面的渲染
    :param _id: 博客的_id
    :return: 渲染一个编辑页面
    """
    # 获取种类
    categories = apis.get_categories()
    # 获取未完成草稿
    drafts = mongo.db.draft.find({})
    drafts_list = []    # 不可以直接使用drafts，因为drafts会变化
    # drafts的type是pymongo.cursor.Cursor，draft的type是dict
    for draft in drafts:
        # 判断是否已经存在草稿
        if draft['blog_id'] == _id:
            # 存在，就直接重定向到相应的草稿
            draft_id = str(draft['_id'])
            return redirect('/admin/edit/draft/' + draft_id)
        drafts_list.append(draft)

    # 获取草稿数目
    draft_count = drafts.count()
    draft_id = mongo.db.draft.insert({})
    blog = mongo.db.blog.find_one({'_id': ObjectId(_id)})
    blog_id = str(blog['_id'])

    # 把tag列表转换为可显示的字符串
    tmptag = ''
    for tag in blog['tags']:
        tmptag += tag
        tmptag += ', '
    blog['tags'] = tmptag[:-2]
    return render_template('admin_modify.html', **locals())

@login_required
def admin_draft_edit(_id):
    """
    :param _id: 草稿的_id
    :return:
    """
    categories = apis.get_categories()
    drafts = mongo.db.draft.find({})
    # fix 14-2-25: 草稿列表的显示
    drafts_list = []
    for draft in drafts:
        if str(draft['_id']) != _id:    # 正在编辑的草稿
            drafts_list.append(draft)

    draft_count = mongo.db.draft.find({}).count() - 1   # 因为要减去正在编辑的草稿
    draft_id = _id
    blog = mongo.db.draft.find_one({'_id': ObjectId(_id)})  # blog实际上是个草稿对象
    blog_id = blog['blog_id']
    tmptag = ''
    for tag in blog['tags']:
        tmptag += tag
        tmptag += ', '
    blog['tags'] = tmptag[:-2]
    return render_template('admin_modify.html', **locals())
